package cn.jhz.learn.community_dynamic.security.handler;

import cn.jhz.learn.community_dynamic.common.bean.JsonData;
import cn.jhz.learn.community_dynamic.model.UserEntity;
import cn.jhz.learn.community_dynamic.security.helper.LoginHelper;
import cn.jhz.learn.community_dynamic.security.helper.ViewAdpt;
import cn.jhz.learn.community_dynamic.security.manager.JwtManager;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.jose4j.jwk.RsaJsonWebKey;
import org.jose4j.lang.JoseException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class JsonLoginSuccessHandler implements AuthenticationSuccessHandler {

    private final JwtManager jwtManager;
    private final ObjectMapper mapper;

    @Autowired
    public JsonLoginSuccessHandler(JwtManager jwtManager, ObjectMapper mapper) {
	super();
	this.jwtManager = jwtManager;
	this.mapper = mapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
	    Authentication authentication) {
	try {
	    // 生成token，并把token加密相关信息缓存，具体请看实现类
	    RsaJsonWebKey rsaJsonWebKey = jwtManager
		    .newRsaJsonWebKey(((UserDetails) authentication.getPrincipal()).getUsername());
	    String token = jwtManager.newInstance(((UserDetails) authentication.getPrincipal()).getUsername(),
		    rsaJsonWebKey);
	    jwtManager.clearRsaJsonWebKey(((UserDetails) authentication.getPrincipal()).getUsername());
	    jwtManager.rsaJsonWebKey(rsaJsonWebKey, ((UserDetails) authentication.getPrincipal()).getUsername());
	    response.setHeader("Authorization", "Bearer " + token);
	    response.setCharacterEncoding("UTF-8");

	    try (PrintWriter writer = response.getWriter()) {
		String jsonStr = mapper.writeValueAsString(JsonData.newSuccessInstance("登陆成功", request.getRequestURI().equals("/api/wbms/user/account_login")
			? ViewAdpt.newWbmsDetailsInstance(((UserEntity) LoginHelper.getLoginUser().get()))
			: this.newAppDetailsInstance((UserEntity) LoginHelper.getLoginUser().get())));
		writer.print(jsonStr);
	    } catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	    }
	} catch (JoseException e) {
	    e.printStackTrace();
	}
	LoginHelper.clear();
    }

    private Map<String, Object> newAppDetailsInstance(UserEntity user) {
	Map<String, Object> data = new HashMap<>();

	data.put("id", user.getLoginId());
	data.put("username", user.getUsername());
	data.put("userpic", user.getUserpic());
	data.put("phone", user.getPhone());
	data.put("email", user.getEmail());
	data.put("status", user.getStatus());
	data.put("create_time", user.getRegistrationTime());
	data.put("logintype", "account");
	data.put("userinfo", user.getUserInfo());

	return data;
    }
}